<?php

namespace app\exam\controller;

use app\common\model\ExamList;
use app\common\model\ExamStudent;
use app\common\model\ExamType;
use app\common\model\Qbank;
use app\common\model\QbankName;
use think\Request;
use think\Session;

class Index extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        dump(Session::get());
    }

    /**获取试卷编号然后调取试卷返回json字符串，用户判断部分只经过测试，未进行正式校验
     * @return mixed|string
     */
    public function answer($id)
    {
//        return Qbank::get(4)->qans;
        $exam = ExamStudent::get($id);
        $uid = 1;
//        dump($id);
//        if (is_null($exam->uid) || $exam->uid != $uid) {
//            return '非当前试卷用户';
//        }
        $question_id_all = json_decode($exam->qid);
        Session::set('exam_id', $id);
        $exam_paper = array();
        $exam_paper['exam_id'] = $id;
        $exam_paper['exam_type'] = $exam->QbankName->bank_name;
        $test = 0;
        $num=1;
        $abc=array("一","二","三","四","五");
        for ($i = 1; $i < 6; $i++) {
            switch ($i) {
                case '1':
                    $qtype = 'Single';
                    break;
                case '2':
                    $qtype = 'Multiple';
                    break;
                case'3':
                    $qtype = 'judge';
                    break;
                case '4':
                    $qtype = 'Completion';
                    break;
                case '5':
                    $qtype = 'essay';
                    break;
            }
            $exam_paper[$qtype . '_num'] = 0;
        }
        foreach ($question_id_all as $question_type => $question_nums) {
            $question = array();
            switch ($question_type) {
                case 'q1':
                    $question['type'] = 'Single';
                    break;
                case 'q2':
                    $question['type'] = 'Multiple';
                    break;
                case'q3':
                    $question['type'] = 'judge';
                    break;
                case 'q4':
                    $question['type'] = 'Completion';
                    break;
                case 'q5':
                    $question['type'] = 'essay';
                    break;
            }
            $exam_paper[$question['type'] . '_num'] = count((array)$question_nums);
if ($exam_paper[$question['type'].'_num']!=0){
    $exam_paper[$question['type'].'_title']=$abc[$test];
    $test++;
}
            foreach ($question_nums as $key => $question_num) {
                $question['id'] = $num;
                $que = Qbank::get($question_num);
                $question['content'] = $que->content;
                $qa = $que->qans;
                $q = json_decode($qa);
                if (strpos($qa, 'img') === false) {
                } else {
                    $question['style'] = 'img';
                }

                $question['qnum'] = $que->qnum;
                $question['qans'] = $q;
                $exam_paper['question'][] = $question;
                $num++;
            }
        }
        $a = json_encode($exam_paper);
        file_put_contents('exam.json',$a);
        return $a;
    }

//    生成试卷
    public function start()
    {
        $id = '1';//考试试卷类型编号，后台设置
        $exam_setting = ExamType::get($id);
        $setting = json_decode($exam_setting->setting);
//        $exam_set['time'] = $setting->time;
        $exam_set['exam_type'] = $id;
        $exam_set['uid'] = Session::get('user')['user_id'];
        $questions = array();
        $answers = array();
        foreach ((array)$setting->questions as $qtype => $question_number) {
            $qtype = str_replace('q', '', $qtype);
            if ($question_number==0){

            }else{
            if ($qtype == 'q4') {
                $score = $setting->score->q4;
                $scores = $score * $question_number;
                $list = $this->sum($question_number, $scores, 6, 1);
                foreach ($list as $k => $li) {
                    if ($li == 0) {
                        unset($list[$k]);
                    } else {
                        $q4a = Qbank::where('qbank', $exam_setting->qbank)->where('qtype', 'q4')->where('qnum', $k)->order('rand()')->limit($li)->select();
                        foreach ($q4a as $q4) {
                            $ques[] = $q4;
                        }
                    }
                }

            } else {
                $ques = Qbank::where('qbank', $exam_setting->qbank)->where('qtype', $qtype)->order('rand()')->limit($question_number)->select();
            }
            foreach ((array)$ques as $key => $question) {
                $questions['q' . $qtype]['q_' . ($key + 1)] = $question->qid;
                $answers['q' . $qtype]['q_' . ($key + 1)] = $question->qa;
            }
        }}

        $exam_set['qid'] = json_encode($questions);
        $exam_set['aid'] = json_encode($answers);
        $exam_type = new ExamStudent();
        $exam_type->save($exam_set);
        file_put_contents('1.json',json_encode($exam_set));
        dump($exam_type->exam_id);
        $this->answer($exam_type->exam_id);

    }

    public function marking()
    {
//        $answers = Request::instance()->port();
        $answers = file_get_contents('1.json');
        $answers = json_decode($answers);
//        $id=Session::get('exam_id');
        $id = 42;
        $exam = ExamStudent::get($id);
        $correct_answers = json_decode($exam->aid);
        $exam_setting = ExamType::get(1)->setting;
        $setting = json_decode($exam_setting);
        foreach ((array)$setting->questions as $key => $qnum) {
            $qnums[$key] = $qnum;
        }
        $i = 1;
        $cor_anss['exam_id'] = $id;
        $typelist = array();
        foreach ((array)$correct_answers as $type => $correct) {
            foreach ((array)$correct as $cor_ans) {
                $cor_anss[$i] = '';
                if ($type == 'q4') {
                    $cor_anss[$i] = explode(',', $cor_ans);

                } elseif ($type == 'q5') {
                    $cor_anss[$i] = '';
                } else {
                    $cor_anss[$i] = $cor_ans;
                }
                $typelist[$i]['qtype'] = $type;
                $i++;
            }
        }

        foreach ((array)$answers as $num => $answer) {
            $a_num = str_replace('Q', '', $num);
            if (is_numeric($a_num)) {
                $anss[$a_num] = $answer;
            } else {
                $a_num_ex = explode(',', $a_num);
                $anss[$a_num_ex[0]][$a_num_ex[1]] = $answer;
            }
        }
        ksort($anss);
        $q5all = array();
        $ans_num = array('q1' => '0', 'q2' => '0', 'q3' => '0', 'q4' => '0', 'q5' => '0');
        foreach ($anss as $key => $ans) {

            if (is_array($ans)) {
                ksort($ans);
                $ans = array_merge($ans);
//                多选题逻辑
                if ($typelist[$key]['qtype'] == 'q2') {
                    $anss = '';
                    foreach ($ans as $an) {
                        $anss .= $an->value;

                    }

                    if ($anss == $cor_anss[$key]) {
                        $ans_num[$typelist[$key]['qtype']]++;
                    }
                } else {
//                    填空题逻辑
                    foreach ($ans as $k => $an) {
                        //
                        if ($an->value == $cor_anss[$key][$k]) {
                            $ans_num[$typelist[$key]['qtype']]++;
                        }
                        $a=1;
                    }
                }
            } else {
//                问答题保存
                if ($typelist[$key]['qtype'] == 'q5') {
                    $q5all[] = $ans->value;
                } else {
//                单选判断逻辑
                    if ($ans->value == $cor_anss[$key]) {
                        $ans_num[$typelist[$key]['qtype']]++;
                    }
                }
            }
        }
        $object_score = 0;
        foreach ((array)$setting->score as $k => $v) {
            $object_score = $object_score + $ans_num[$k] * $v;
        }
        dump($object_score);

        $exam_list = new ExamList();
        $exam_list->exam_id = Session::get($answers->exam_id);
        $exam_list->uid = $exam->uid;
        $exam_list->exam_answers = json_encode($q5all);
        $exam_list->object_score = $object_score;
        $exam_list->save();

//        json_encode($q5all);


        //获取便于比较的正确答案
        dump($ans_num);


    }

    public function submit()
    {
        dump(Request::instance()->post());
        if (Request::instance()->isPost()) {
            $exam_result = Request::instance()->post();

        }
    }

    public function sum($n, $sum_n, $max, $min)
    {
        $sum = 0;
        $arr = array();
//        最大分值
//        $max=6;
//        最小分值
//        $min=1;
//        总分
//        $sum_n = 40;
//        题目数量
//        $n=10;
        for ($i = 1; $i < $max + 1; $i++) {
            $list[$i] = 0;
        }
        $i = 1;
        while ($i <= $n) {
            $a = rand($min, $max);
            if (($sum_n - $sum - $a) >= $min * ($n - $i) && ($sum_n - $sum - $a) <= $max * ($n - $i)) {
                $sum = $sum + $a;
                $list[$a] = $list[$a] + 1;
                $arr[] = $a;
                $i++;
            }
        }
        return $list;


    }

}
